const express = require('express');

const pool = require( '../utils/pool.js' );
const random = require( '../utils/random.js' );

const separator = '、' ;

const router = express.Router();

router.get( '/' , (req,resp)=>{
    let sql = 'SELECT id , name FROM t_classes ' ;
    let handler = ( error , results , fields )=>{
        resp.render( 'add' , { classes: results } );
    }
    pool.execute( sql , handler );
});

router.post( '/student/add' , (req,resp) => {
    let id = random.next();
    let name = req.body.name ;
    let age = req.body.age ;
    let gender = req.body.gender ;
    let hobby = req.body.hobby ;
    let hobbies = hobby.join( separator );
    console.log( hobbies );
    let cid = req.body.classId ;

    let sql = 'INSERT INTO t_students (id,name,age,gender,hobbies,cid) VALUES (?,?,?,?,?,?)' ;
    let params = [ id , name , age , gender , hobbies , cid ];
    let handler = (err,results,fields) => {
        if( err ){
            throw err ;
        }
        console.log( results );
        resp.redirect( '/student/list' );
    }
    pool.execute( sql , params , handler );
});

router.get( '/student/list' , (req,resp)=> {

    let sql = `SELECT s.id , s.name , s.age , s.gender , c.name className 
               FROM t_students s 
               JOIN t_classes c 
               ON s.cid = c.id ` ;

    let handler = (error,results,fields) => {
        resp.render( 'list' , { students: results });
    }
    pool.execute( sql , handler );
    
});

router.get( '/student/remove/:id' ,(req,resp) => {
    let id = req.params.id ;
    pool.execute( 'DELETE FROM t_students WHERE id = ? ' , [ id ] , (error,results,fields) => {
        resp.redirect( '/student/list' );
    });
});

router.get( '/student/edit/:id' , (req,resp)=>{

    let id = req.params.id ;

    pool.execute( 'SELECT id,name,age,gender,hobbies,cid FROM t_students WHERE id = ? ' , [ id ] , (error,results)=>{
        if( error ) {
            throw error ;
        }
        let student = results[ 0 ];
        console.log( student );
        student.hobbies = student.hobbies.split( separator );
        console.log( student );
        pool.execute( 'SELECT id , name FROM t_classes' , ( err , rows )=>{
            resp.render( 'edit' , { stu : student , classes: rows } );
        } );
    });
});

router.post( '/student/edit' , (req,resp) => {
    let id = req.body.id ;
    let name = req.body.name ;
    let age = req.body.age ;
    let gender = req.body.gender ;
    let hobby = req.body.hobby ;
    let hobbies = hobby.join( separator );
    let cid = req.body.classId ;

    let sql = 'UPDATE t_students SET name = ? , age = ? , gender = ? , hobbies = ? , cid = ? WHERE id = ?' ;
    let params = [ name , age , gender , hobbies , cid , id ];
    let handler = error => {
        if( error ) {
            throw error ;
        }
        resp.redirect( '/student/list' );
    }
    pool.execute(sql,params,handler);
});

module.exports = router ;